package utils

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"guns-go/global"
	"guns-go/model/response"
	"strconv"
)

func DefaultPage(c *gin.Context, table *gorm.DB) (int, int, *gorm.DB) {

	var pageSize = 20
	var pageNo = 1

	pageSizeString := c.Query("pageSize")

	if pageSizeString != "" {
		size, _ := strconv.Atoi(pageSizeString)
		pageSize = size
	}

	pageNoString := c.Query("pageNo")

	if pageNoString != "" {
		page, _ := strconv.Atoi(pageNoString)
		pageNo = page
	}

	offset := pageSize * (pageNo - 1)

	return pageNo, pageSize, table.Limit(pageSize).Offset(offset)
}

func GetNoDbPage(c *gin.Context) (int, int) {

	var pageSize = 20
	var pageNo = 1

	pageSizeString := c.Query("pageSize")

	if pageSizeString != "" {
		size, _ := strconv.Atoi(pageSizeString)
		pageSize = size
	}

	pageNoString := c.Query("pageNo")

	if pageNoString != "" {
		page, _ := strconv.Atoi(pageNoString)
		pageNo = page
	}

	return pageNo, pageSize
}

func CoverToPageResult(pageNo int, pageSize int, totalCount int64, data interface{}) (result *response.PageResult) {

	pageResult := new(response.PageResult)

	pageResult.Rows = data
	pageResult.TotalRows = int(totalCount)
	pageResult.PageNo = pageNo
	pageResult.PageSize = pageSize
	pageResult.TotalPage = (int(totalCount) + pageSize - 1) / pageSize
	pageResult.Rainbow = Rainbow(pageNo, pageResult.TotalPage, global.RainbowNum)

	return pageResult
}

func Rainbow(pageNo int, totalPage int, displayCount int) []int {

	isEven := displayCount%2 == 0
	left := displayCount / 2
	right := displayCount / 2
	length := displayCount
	if isEven {
		right = right + 1
	}

	if totalPage < displayCount {
		length = totalPage
	}

	result := make([]int, length)

	var i int
	if totalPage >= displayCount {
		if pageNo <= left {
			for i = 0; i < len(result); i = i + 1 {
				result[i] = i + 1
			}
		} else if pageNo > totalPage-right {
			for i = 0; i < len(result); i = i + 1 {
				result[i] = i + totalPage - displayCount + 1
			}
		} else {
			for i = 0; i < len(result); i = i + 1 {
				if isEven {
					result[i] = i + pageNo - left + 1
				} else {
					result[i] = i + pageNo - left + 0
				}
			}
		}
	} else {
		for i = 0; i < len(result); i = i + 1 {
			result[i] = i + 1
		}
	}

	return result
}
